
<template>
  <div>
    <router-view></router-view>

    <page-layout class="task">
      <a-row :gutter="[16, 16]">
        <a-col :span="2">
          <a-dropdown>
            <a-menu slot="overlay" @click="handleMenuClick">
              <a-menu-item key="1"> <a-icon type="user" />全部</a-menu-item>
              <a-menu-item key="2"> <a-icon type="user" />吴松泽</a-menu-item>
              <a-menu-item key="3"> <a-icon type="user" />叶明保</a-menu-item>
            </a-menu>
            <a-button style="margin-left: 8px">
              全部 <a-icon type="down" />
            </a-button>
          </a-dropdown>
        </a-col>
      </a-row>

      <a-row :gutter="[16, 16]">
        <a-col :span="8">
          <a-button :type="status==0?'primary':''" @click="statusClick(0)"> 所有 </a-button>
          <a-button :type="status==1?'primary':''" @click="statusClick(1)">未开始</a-button>
          <a-button :type="status==2?'primary':''" @click="statusClick(2)">进行中</a-button>
          <a-button :type="status==3?'primary':''" @click="statusClick(3)">已完成</a-button>
          <a-button :type="status==4?'primary':''" @click="statusClick(4)">已延期</a-button>
          <a-button :type="status==5?'primary':''" @click="statusClick(5)">已中止</a-button>
          <a-button :type="status==6?'primary':''" @click="statusClick(6)">已关闭</a-button>
        </a-col>
        <a-col :span="3">
          <a-input-search
            placeholder="请输入任务名称"
            v-model="searchText"
            @pressEnter="handelsearch"
          ></a-input-search>
        </a-col>
        <a-col :span="2" push="10">
          <a-button
            v-if="userInfo.permissions.task_insert"
            type="primary"
            @click="
              $router.push({
                path: '/task/add',
                query: { random: random }
              })
            "
          >
            新增
          </a-button>
        </a-col>
      </a-row>

      <!-- <a-card> -->
      <div class="tabel-wrapper">
        <standard-table
          :columns="columns"
          :dataSource="dataSource"
          @change="onChange"
          :pagination="pagination"
          size="large"
          :loading="loading"
        >
          <div slot="truly_time" slot-scope="{ text, record }">
            <template v-if="text != null">
              <a
                style="text-decoration: underline"
                @click="log_info(record.key)"
                title="点击查看任务日志"
              >
                {{ text }}
              </a>
            </template>
            <template v-else>
              <a style="text-decoration: underline"> 暂未开始 </a>
            </template>
          </div>
          <div slot="status" slot-scope="{ text }">
            <template v-if="text == 2">
              <a-tag color="#FF6D25"> 进行中 </a-tag>
            </template>
            <template v-else-if="text == 3">
              <a-tag color="#f5222d"> 已完成 </a-tag>
            </template>
            <template v-else-if="text == 4">
              <a-tag color="#f5222d"> 超时 </a-tag>
            </template>
            <template v-else-if="text == 5">
              <a-tag color="#f5222d"> 已中止 </a-tag>
            </template>
            <template v-else-if="text == 6">
              <a-tag color="#4E25FF"> 测试验收 </a-tag>
            </template>
            <template v-else>
              <a-tag color="#2591FF"> 待开始 </a-tag>
            </template>
          </div>

          <div slot="action" slot-scope="{ text, record }">
            <a
              v-if="userInfo.permissions.task_detail"
              :href="`#/task/detail?random=${random}&&id=${record.key}`"
              style="margin-right: 8px"
              >查看</a
            >
            <a
              v-if="userInfo.permissions.task_edit"
              :href="`#/task/add?random=${random}&&id=${record.key}`"
              style="margin-right: 8px"
              >| 编辑</a
            >
            <a-popconfirm
              v-if="record.status < 2 && userInfo.permissions.task_delete"
              title="确定删除该任务吗?"
              ok-text="是的"
              cancel-text="取消"
              @confirm="() => confirm(record.key)"
            >
              <a>| 删除</a>
            </a-popconfirm>
            <template
              v-if="
                text.engineer_id === userId && userInfo.permissions.task_start
              "
            >
              <a href="">| </a>
              <a-popconfirm
                title="确定开始此任务吗?"
                ok-text="是的"
                cancel-text="取消"
                v-if="!record.log_status || record.log_status == 3"
                @confirm="() => start_task(record.key)"
              >
                <a>
                  <!-- {{ record.log_status }} -->
                  <a-icon
                    style="margin-right: 5px"
                    type="play-circle"
                    title="开始"
                  ></a-icon
                ></a>
              </a-popconfirm>
              <a>
                <a-icon
                  v-if="record.log_status == 1"
                  @click="showPauseModal(record.key)"
                  type="pause-circle"
                  title="暂停"
                  style="margin-right: 5px"
                ></a-icon>
              </a>
              <a-modal
                title="任务暂停备注"
                destroyOnClose
                :visible="pause_visible"
                :confirm-loading="pause_confirmLoading"
                @ok="() => pause_handleOk(record.key)"
                @cancel="pause_handleCancel"
              >
                <a-form
                  id="components-form-demo-normal-login"
                  ref="pause_form"
                  :form="pause_form"
                  class="login-form"
                  v-bind="{
                    labelCol: { span: 6 },
                    wrapperCol: { span: 14 }
                  }"
                >
                  <a-form-item label="任务暂停备注">
                    <a-textarea
                      v-decorator="[
                        'desc',
                        {
                          rules: [
                            { required: true, message: '此处填写任务暂停备注!' }
                          ]
                        }
                      ]"
                      placeholder="此处填写任务暂停备注"
                    >
                    </a-textarea>
                  </a-form-item>
                </a-form>
              </a-modal>
              <a>
                <a-icon
                  @click="showSuspendModal(record.key)"
                  type="stop"
                  title="中止"
                  style="margin-right: 5px; color: #f5222d"
                ></a-icon>
              </a>
              <a-modal
                title="中止任务"
                :visible="suspend_visible"
                :confirm-loading="suspend_confirmLoading"
                @ok="suspend_handleOk(record.key)"
                @cancel="suspend_handleCancel"
              >
                <a-form
                  id="components-form-demo-normal-login"
                  ref="suspend_form"
                  :form="suspend_form"
                  class="login-form"
                  v-bind="{
                    labelCol: { span: 6 },
                    wrapperCol: { span: 14 }
                  }"
                >
                  <a-form-item label="中止原因">
                    <a-textarea
                      v-decorator="[
                        'desc',
                        {
                          rules: [
                            { required: true, message: '请备注任务中止原因!' }
                          ]
                        }
                      ]"
                      placeholder="任务中止原因"
                    >
                    </a-textarea>
                  </a-form-item>
                </a-form>
              </a-modal>
              <a-popconfirm
                title="确定完成此任务吗?"
                ok-text="是的"
                cancel-text="取消"
                @confirm="() => finish_task(record.key, '完成任务')"
              >
                <a>
                  <a-icon
                    type="check-circle"
                    title="完成"
                    style="margin-right: 5px"
                  />
                </a>
              </a-popconfirm>
            </template>
          </div>
          <template slot="statusTitle">
            <a-icon @click.native="onStatusTitleClick" type="info-circle" />
          </template>
        </standard-table>
      </div>
      <a-modal
        v-model="log_visible"
        title="任务日志"
        ok-text="确认"
        @ok="hideModal"
      >
        <a-table :columns="log_columns" :data-source="log_data"> </a-table>
      </a-modal>
      <!-- </a-card> -->
    </page-layout>
  </div>
</template>

<script>
import PageLayout from "@/layouts/PageLayout";
import StandardTable from "@/components/table/StandardTable";
import {
  list,
  deleteItem,
  finish,
  suspend,
  pause,
  start,
  logs
} from "@/services/task";
import Cookie from "js-cookie";
// import { mapMutations } from "vuex";
const columns = [
  {
    title: "ID",
    dataIndex: "key"
  },
  {
    title: "关联需求",
    dataIndex: "requirement_name"
  },
  {
    title: "任务名称",
    dataIndex: "title"
  },
  {
    title: "工程师",
    dataIndex: "engineer_name"
  },
  {
    title: "对接人",
    dataIndex: "docking_name"
  },
  {
    title: "任务状态",
    dataIndex: "status",
    scopedSlots: { customRender: "status" }
  },
  {
    title: "总耗时",
    dataIndex: "truly_time",
    scopedSlots: { customRender: "truly_time" }
  },
  {
    title: "操作",
    scopedSlots: { customRender: "action" },
    align: "center"
  }
];
const log_columns = [
  {
    title: "id",
    dataIndex: "id",
    key: "id"
  },
  {
    title: "开始时间",
    dataIndex: "created_at",
    key: "created_at",
    ellipsis: true
  },
  {
    title: "备注内容",
    dataIndex: "desc",
    key: "desc",
    width: 120
  },
  {
    title: "耗时",
    dataIndex: "hours",
    scopedSlots: { customRender: "hours" },
    key: "hours",
    width: 120
  },
  {
    title: "结束时间",
    dataIndex: "end_at",
    key: "end_at",
    ellipsis: true
  }
];

export default {
  name: "demand",
  components: { PageLayout, StandardTable },
  data() {
    return {
      userInfo: [],
      log_columns,
      log_visible: false,
      log_data: "",
      pause_visible: false,
      pause_form: this.$form.createForm(this, { name: "desc" }),
      pause_confirmLoading: false,
      suspend_visible: false,
      suspend_form: this.$form.createForm(this, { name: "desc" }),
      suspend_confirmLoading: false,
      userId: "",
      searchText: "",
      status: "",
      random: "",
      loading: true,
      desc: "需求管理中心",
      columns: columns,
      dataSource: [],
      selectedRows: [],
      pagination: {
        size: "small",
        showSizeChanger: true,
        showQuickJumper: true,
        poposition: "bottom",
        pageSize: 5,
        current: 1,
        total: 0
      }
    };
  },
  authorize: {
    deleteRecord: "delete"
  },
  activated() {
    const { pageSize, current } = this.pagination;
    this.random = Math.random();
    this.loadTableData({ limit: pageSize, page: current, status: this.status});
  },
  created() {
    let userInfo = JSON.parse(window.localStorage.getItem("admin.user"));
    this.userInfo = userInfo;
    // 初始数据
    const { pageSize, current } = this.pagination;
    this.random = Math.random();
    this.loadTableData({ limit: pageSize, page: current, status: this.status});
  },
  mounted() {
    this.userId = +Cookie.get("Authorization").split(" ")[1];
    // console.log(typeof this.userId);
  },
  methods: {
    //日志弹窗控制方法
    hideModal() {
      this.log_visible = false;
    },
    log_info(id) {
      this.log_visible = true;
      logs(id).then((res) => {
        console.log(res.data.data);
        if (res.data.code === 20000) {
          this.log_data = res.data.data;
          // this.$message.success(res.data.message);
          setTimeout(() => {
            const { pageSize, current } = this.pagination;
            this.loadTableData({ limit: pageSize, page: current, status: this.status});
          }, 100);
        }
      });
    },
    start_task(id) {
      start(id).then((res) => {
        console.log(res.data.code);
        if (res.data.code === 20000) {
          this.$message.success(res.data.message);
          setTimeout(() => {
            const { pageSize, current } = this.pagination;
            this.loadTableData({ limit: pageSize, page: current, status: this.status});
          }, 500);
        }
      });
    },
    finish_task(id, desc) {
      finish({ id, desc }).then((res) => {
        console.log(res.data.code);
        if (res.data.code === 20000) {
          this.$message.success(res.data.message);
          setTimeout(() => {
            const { pageSize, current } = this.pagination;
            this.loadTableData({ limit: pageSize, page: current, status: this.status});
          }, 500);
        }
      });
    },
    showSuspendModal() {
      this.suspend_visible = true;
    },

    suspend_handleOk(id) {
      this.suspend_form.validateFields((err, values) => {
        if (!err) {
          suspend({ id, ...values }).then((res) => {
            console.log(res.data.code);
            if (res.data.code === 20000) {
              this.$message.success(res.data.message);
              this.suspend_form.resetFields();
              setTimeout(() => {
                const { pageSize, current } = this.pagination;
                this.loadTableData({ limit: pageSize, page: current, status: this.status});
                this.suspend_visible = false;
              }, 500);
            }
          });
        }
      });
    },
    suspend_handleCancel() {
      // console.log('Clicked cancel button');
      this.suspend_visible = false;
    },
    showPauseModal(id) {
      this.pauseid = id;
      this.pause_visible = true;
    },
    pause_handleOk() {
      this.pause_form.validateFields((err, values) => {
        if (!err) {
          pause({ id: this.pauseid, ...values }).then((res) => {
            console.log(res.data.code);
            if (res.data.code === 20000) {
              this.$message.success(res.data.message);
              this.pause_form.resetFields();
              setTimeout(() => {
                const { pageSize, current } = this.pagination;
                this.loadTableData({ limit: pageSize, page: current });
                this.pause_visible = false;
              }, 1000);
            }
          });
        }
      });
    },
    pause_handleCancel() {
      // console.log('Clicked cancel button');
      this.pause_visible = false;
    },

    // 请求table 的数据
    // obj 请求的字段
    loadTableData(obj) {
      this.loading = true;
      list(obj).then((res) => {
        // console.log(res.data, 222222);
        // 关闭loading
        this.loading = false;
        if (res.data.code === 20000) {
          const { current_page, total, per_page } = res.data.data;
          Object.assign(this.pagination, {
            total: parseInt(total),
            current: parseInt(current_page),
            pageSize: parseInt(per_page)
          });
          this.dataSource = res.data.data.data.map((item) => {
            // console.log(item);
            const {
              requirement_name,
              task_id,
              created_at,
              title,
              engineer_name,
              engineer_id,
              docking_name,
              docking_id,
              status,
              log_status,
              truly_time
            } = item;
            return {
              key: task_id,
              requirement_name,
              created_at: created_at && created_at.split(" ")[0],
              title: title || "未知",
              engineer_name: engineer_name || "未知",
              docking_name: docking_name || "未知",
              engineer_id,
              docking_id,
              status,
              log_status,
              truly_time
            };
          });
        }
      });
    },
    handelsearch() {
      this.loadTableData({
        limit: this.pagination.pageSize,
        title: this.searchText,
        status: this.status
      });
      // this.searchText = "";
    },

    onClear() {
      this.$message.info("您清空了勾选的所有行");
    },
    onStatusTitleClick() {
      this.$message.info("你点击了状态栏表头");
    },
    onChange(e) {
      const { current, pageSize } = e;
      this.loadTableData({ limit: pageSize, page: current, title: this.searchText, status: this.status});
    },
    statusClick(e) {
      this.status = e;
      this.loadTableData({title: this.searchText, status: e});
    },
    handleMenuClick(e) {
      if (e.key === "delete") {
        this.remove();
      }
    },
    cancel(key) {
      this.$message.info(`点击了取消,行数为${key + 1}行`);
    },
    confirm(key) {
      // 发起删除的请求
      deleteItem(key).then((res) => {
        // console.log(res, "delete");
        // 成功
        if (res.data.code === 20000) {
          // 提示信息
          this.$message.success({
            content: res.data.message || "删除成功~"
          });
          // 删除成功后重新获取数据
          const { pageSize, current } = this.pagination;
          this.loadTableData({ limit: pageSize, page: current ,status: this.status});
        } else {
          this.$message.error(res.data.message || "删除失败！");
        }
      });
    }
  }
};
</script>

<style lang="less">
.search-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;

  > div {
    .search-input input {
      padding-left: 45px !important;
    }
    display: flex;
    width: 60%;
    .ant-input-affix-wrapper {
      display: inline-block;
      width: calc(100% - 150px);
      height: 54px !important;
      input {
        height: 100% !important;
      }
      input::-webkit-input-placeholder {
        color: #9999;
        font-size: 16px;
      }

      input::-moz-placeholder {
        /* Mozilla Firefox 19+ */
        color: #9999;
        font-size: 16px;
      }

      input:-moz-placeholder {
        /* Mozilla Firefox 4 to 18 */
        color: #9999;
        font-size: 16px;
      }

      input:-ms-input-placeholder {
        /* Internet Explorer 10-11 */
        color: #9999;
        font-size: 16px;
      }
    }
    .search-button {
      margin-left: 30px;
      width: 120px;
      height: 54px;
    }
  }
}
.task {
  .tabel-wrapper {
    border-radius: 5px;
    // min-height: 450px;
    background-color: #fff;
    color: #1f1f1f;
    .ant-pagination {
      margin-top: 60px !important;
    }
    tr {
      height: 66px !important;
      // padding-left: 10px;
    }
    .ant-table-thead {
      padding-left: 20px;
      background: #effaff;
      & > tr > th {
        background: #effaff !important;
      }
    }
    .ant-table-tbody {
      padding-left: 20px;
    }
    .ant-table-pagination.ant-pagination {
      float: unset !important;
      text-align: center;
    }
  }
}
</style>
